package com.easysoft.framework.action;
import com.easysoft.commons.utils.StringUtils;
import com.easysoft.commons.utils.UUIDUtils;
import com.easysoft.commons.utils.WebConstants;
import com.easysoft.framework.annotation.logs.SystemControllerLog;
import com.easysoft.framework.beans.Page;
import com.easysoft.framework.menu.model.SysMenu;
import com.easysoft.framework.menu.model.SysMenuQuery;
import com.easysoft.framework.menu.model.SysMenuView;
import com.easysoft.framework.menu.service.SysMenuService;;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by try on 2017/7/5.
 */

@RestController
@RequestMapping(value = SystemMenuAction.BASE_VIEW)
public class SystemMenuAction {

    public static final String BASE_VIEW = "/menu";
    private final static Logger logger = LoggerFactory.getLogger(SystemMenuAction.class);

    @Autowired
    @Qualifier("service.SysMenuService")
    private SysMenuService sysMenuService;

    /**
     *  获取菜单列表
     * @param page
     * @param query
     * @return
     */
    @RequestMapping(value = "/listMenu",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView listMenu(Page page, SysMenuQuery query) {
        logger.info("Call SystemMenuAction.listMenu({},{})", page.toString(), query.toString());

        List<SysMenuView> listMenu = sysMenuService.selectSysMenuByPage(page,query);

        /**
         * 查询出 父类菜单 通过菜单层级 1 父类层级
         */
        List<SysMenuView> parentListMenu = sysMenuService.selectSysMenuByLevel(1);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/listMenu");
        mv.addObject("page", page); // 返回分页与查询条件
        mv.addObject("query", query); // 返回分页与查询条件
        mv.addObject("listMenu", listMenu); // 返回查询结果集
        mv.addObject("parentListMenu", parentListMenu); // 父类菜单
        return mv;
    }

    /**
     * 查询角色所拥有权限的菜单
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/selectRoleMenu", method = RequestMethod.POST)
    public List<Map<String, Object>> selectRoleMenu(HttpSession session) {
        String userId = (String) session.getAttribute(WebConstants.SESSION_USER_ID);
        logger.info("Call SystemMenuAction.selectRoleMenu()");

        return sysMenuService.getSysMenuTree(userId);
    }

    @RequestMapping(value = "/editMenu",method = RequestMethod.GET)
    public ModelAndView editMenu(String action, @RequestParam(required = false) String id){
        logger.info("Call SystemMenuAction.editMenu({},{})", action, id);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/editMenu");
        List<SysMenuView> parentListMenu = sysMenuService.selectSysMenuByLevel(1);
        mv.addObject("parentListMenu", parentListMenu);
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(id)) {
                return null;
            }
            return mv;
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(id)) {
                return null;
            }
            SysMenu entity = sysMenuService.selectMenuByPrimaryKey(id);
            if (entity == null) {
                return null;
            }
            mv.addObject("entity", entity);
            return mv;
        }
        return null;
    }

    @RequestMapping(value = "/saveMenu", method = RequestMethod.POST)
    public int saveMenu(String action, SysMenu menu, HttpSession session){
        logger.info("Call SystemMenuAction.saveMenu({},{})", action,menu.toString());
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(menu.getId())) {
                return 0;
            }
            return addSysMenu(menu,session);
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(menu.getId())) {
                return 0;
            }
            return updateSysMenu(menu,session);
        }
        return 0;
    }


    /**
     * 保存菜单
     *
     * @param sysMenu
     * @param session
     * @return 持久化后的主键，保存失败返回null
     */
    @SystemControllerLog(description = "新增菜单信息")
    public int addSysMenu(SysMenu sysMenu, HttpSession session) {

        String userId = (String) session.getAttribute(WebConstants.SESSION_USER_ID);

        logger.info("Call SystemMenuAction.saveSysMenu({}, {})", sysMenu.toString(), userId);

        // 设置操作人
        sysMenu.setOperator(userId);

        return sysMenuService.saveMenu(sysMenu);
    }

    /**
     * 根据主键更新对应的记录（不包含null字段）
     *
     * @param sysMenu
     * @return 1：更新成功；0：主键不存在
     */
    @SystemControllerLog(description = "更新菜单信息")
    @RequestMapping(value = "/updateSysMenu", method = RequestMethod.POST)
    public int updateSysMenu(SysMenu sysMenu, HttpSession session) {

        String userId = (String) session.getAttribute(WebConstants.SESSION_USER_ID);

        logger.info("Call SystemMenuAction.updateSysMenu({}, {})", sysMenu.toString(), userId);

        // 设置操作人
        sysMenu.setOperator(userId);

        return sysMenuService.updateSysMenu(sysMenu, userId);
    }

    /**
     * 根据主键查询菜单
     *
     * @param id
     *            主键
     * @return 主键对应的记录，主键不存在则返回null
     */
    @RequestMapping(value = "/viewMenu", method = RequestMethod.POST)
    public SysMenu viewMenu(String id) {

        logger.info("Call SystemMenuAction.viewMenu({})", id);

        return sysMenuService.selectMenuByPrimaryKey(id);
    }

    /**
     * 根据主键删除对应的记录
     *
     * @param id
     *            主键
     * @param session
     * @return 1：删除成功；0：主键不存在 ;-1：存在子节点
     */
    @SystemControllerLog(description = "删除菜单信息")
    @RequestMapping(value = "/deleteMenu", method = RequestMethod.POST)
    public int deleteMenu(String id, HttpSession session) {

        String userId = (String) session.getAttribute(WebConstants.SESSION_USER_ID);

        logger.info("Call SystemMenuAction.deleteMenu({}, {})", id, userId);

        return sysMenuService.deleteSysMenu(id, userId);
    }

    /**
     * 查询菜单链接标识是否已存在
     *
     * @param mid
     *            ,id 链接标识，主键
     * @return
     */
    @RequestMapping(value = "/checkMid", method = RequestMethod.POST)
    public int checkMid(int mid, String id) {
        logger.info("Call SystemMenuAction.checkMid({},{})", mid, id);

        List<SysMenuView> menusList = sysMenuService.checkMid(mid);
        // 修改时去除自己
        if (id != null && !"".equals(id)) {
            for (SysMenuView menus : menusList) {
                if (menus.getId().equals(id)) {
                    menusList.remove(menus);
                    break;
                }
            }
        }
        if (menusList != null && menusList.size() > 0) {
            return 1;
        }
        else {
            return 0;
        }
    }
}
